package com.feihong.txgw.ui.activity.kaika;

import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AlertDialog;
import android.view.View;
import android.widget.TextView;

import com.feihong.txgw.R;
import com.feihong.txgw.message.LoginMessage;
import com.feihong.txgw.ui.activity.base.BaseActivity;
import com.feihong.txgw.view.StatusView;

import java.util.ArrayList;

import butterknife.BindView;
import me.dm7.barcodescanner.zbar.BarcodeFormat;
import me.dm7.barcodescanner.zbar.Result;
import me.dm7.barcodescanner.zbar.ZBarScannerView;
import permissions.dispatcher.NeedsPermission;
import permissions.dispatcher.OnNeverAskAgain;
import permissions.dispatcher.OnPermissionDenied;
import permissions.dispatcher.OnShowRationale;
import permissions.dispatcher.PermissionRequest;
import permissions.dispatcher.RuntimePermissions;

/**
 * Created by Sabirjan on 2017/7/3.
 * TXGWApp.
 * 飞宏电子
 * 扫码（电话卡的条形码）
 */
@RuntimePermissions
public class ScanBarCodeActivity extends BaseActivity implements ZBarScannerView.ResultHandler,View.OnClickListener{
    @BindView(R.id.mZXingScannerView) ZBarScannerView mScannerView;
    @BindView(R.id.scanner_status_layout) StatusView mStatusView;
    @BindView(R.id.scanner_txt_pagetitle) TextView mTitleTv;
    private boolean isNeeds = true;
    @Override
    public void setTheme() {
        isDrakFont = false;
    }
    @Override
    public int setLayoutID() {
        return R.layout.activity_scanner;
    }

    private void openCamera()
    {
        if (isNeeds) {
            // Register ourselves as a handler for scan results.
            mScannerView.setResultHandler(ScanBarCodeActivity.this);
            try {
                    mScannerView.startCamera();          // Start camera on resume
            } catch (Exception ex) {
                ex.printStackTrace();
                showDialog("权限不足", "您没有开启此应用的使用摄像头权限。请到系统设置-->权限管理 开启摄像使用权限。如果您的手机上安装了第三方管家应用（360管家，腾讯管家等），请开启一下摄像头权限！", new DialogInterface.OnDismissListener() {
                    @Override
                    public void onDismiss(DialogInterface dialog) {
                        finish();
                    }
                });
            }
        }
    }
    @Override
    public void onPause() {
        super.onPause();
        mScannerView.stopCamera();
        // Stop camera on pause
    }

    @Override
    public void initView(Bundle savedInstanceState) {
        // mScannerView = new ZXingScannerView(SannerActivity.this);   // Programmatically initialize the scanner view
        mTitleTv.setText("扫描SIM卡条形码");
        setSpecificTitleLayout(mStatusView);
        ArrayList<BarcodeFormat> list = new ArrayList<>();
        list.add(BarcodeFormat.CODE128);
        //二维码
        //   list.add(BarcodeFormat.CODE128);
        ////  list.add(BarcodeFormat.CODE93);
        list.add(BarcodeFormat.CODE39);
        ////     list.add(BarcodeFormat.QRCODE);
        //    list.add();
        mScannerView.setFormats(list);
        ScanBarCodeActivityPermissionsDispatcher.onNeedsPermissionWithCheck(this);
    }

    @Override
    public void bindData() {

    }

    @Override
    public void onUserLogin(LoginMessage loginMessage) {

    }

    @NeedsPermission(Manifest.permission.CAMERA)
    void onNeedsPermission() {
        isNeeds = true;
        openCamera();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        ScanBarCodeActivityPermissionsDispatcher.onRequestPermissionsResult(this, requestCode, grantResults);
    }

    @OnPermissionDenied(Manifest.permission.CAMERA)
    void onPermissionDenied() {
        isNeeds = false;
        showDialog("权限不足", "您没有开启此应用的使用摄像头权限。请到系统设置-->权限管理 开启摄像使用权限。如果您的手机上安装了第三方应用管家（360管家，腾讯管家等），请开启一下摄像头权限！", new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
                finish();
            }
        });
    }

    @OnNeverAskAgain(Manifest.permission.CAMERA)
    void onNeverAskAgain() {

        isNeeds = false;
        showDialog("权限不足", "您没有开启此应用的使用摄像头权限。请到系统设置-->权限管理 开启摄像使用权限。如果您的手机上安装了第三方应用管家（360管家，腾讯管家等），请开启一下摄像头权限！", new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
                finish();
            }
        });
    }
    //扫码返回结果
    @Override
    public void handleResult(Result result) {
        // Do something with the result here
//        Log.v(TAG, result.getContents()); // Prints scan results
//        Log.v(TAG, result.getBarcodeFormat().getName()); // Prints the scan format (qrcode, pdf417 etc.)
        if (result != null && result.getContents() != null) {
            Intent intent = new Intent();
            intent.putExtra("result", result.getContents());
            setResult(1, intent);
            finish();
        }
    }

    @OnShowRationale(Manifest.permission.CAMERA)
    public void kaikaRationaleForCamera(final PermissionRequest request){
        new AlertDialog.Builder(this)
                .setPositiveButton("允许", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(@NonNull DialogInterface dialog, int which) {
                        request.proceed();
                    }
                })
                .setNegativeButton("拒绝", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(@NonNull DialogInterface dialog, int which) {
                        request.cancel();
                    }
                })
                .setCancelable(false)
                .setMessage("请允许获取相机权限")
                .show();
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.iv_back:
                finish();
                break;
            default:break;
        }
    }
}